package cn.xunjie.org.service.impl;

import cn.xunjie.basic.service.impl.BaseServiceImpl;
import cn.xunjie.org.domain.Department;
import cn.xunjie.org.mapper.DepartmentMapper;
import cn.xunjie.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;
    @Override
    public void save(Department department) {
        departmentMapper.save(department);
        this.update(department);

    }



    @Override
    public void update(Department department) {
        String dirPath = "";
        if(department.getParent()==null){
            dirPath = "/"+department.getId();
        }else {
            Department parent = departmentMapper.loadById(department.getParent().getId());
            dirPath = parent.getDirPath() + "/" + department.getId();
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);

    }



   



    @Override
    public List<Department> depttree() {
        //查询出department表的所有数据
        List<Department> departments = departmentMapper.loadAll();
        //创建一个hashmap以department的id为key单条内容为value
        Map<Long, Department> allDepts = new HashMap<>();
        //循环department
        for (Department department : departments) {
            allDepts.put(department.getId(),department);
        }
        //创建一个首级list
        List<Department> fistDepts = new ArrayList<>();
        for (Department tmp : departments) {
            if(tmp.getParent_id()==null){
                //将值存入fistdepts集合
                fistDepts.add(tmp);
            }else {
                //根据getparent-id查到父类
                Department parent = allDepts.get(tmp.getParent_id());
                if (parent != null){
                    //将值存父类的Children
                    parent.getChildren().add(tmp);
                }
            }
        }
        return fistDepts;
    }
}










